package com.Ritany3.subject.domain.service.impl;

import com.Ritany3.subject.common.entity.PageResult;
import com.Ritany3.subject.common.enums.IsDeletedFlagEnum;
import com.Ritany3.subject.common.util.IdWorkerUtil;
import com.Ritany3.subject.common.util.LoginUtil;
import com.Ritany3.subject.domain.convert.SubjectCategoryConverter;
import com.Ritany3.subject.domain.convert.SubjectInfoConverter;
import com.Ritany3.subject.domain.entity.SubjectCategoryBO;
import com.Ritany3.subject.domain.entity.SubjectInfoBO;
import com.Ritany3.subject.domain.entity.SubjectOptionBO;
import com.Ritany3.subject.domain.handler.subject.SubjectTypeHandler;
import com.Ritany3.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.Ritany3.subject.domain.redis.RedisUtil;
import com.Ritany3.subject.domain.service.SubjectCategoryDomainService;
import com.Ritany3.subject.domain.service.SubjectInfoDomainService;
import com.Ritany3.subject.domain.service.SubjectLikedDomainService;
import com.Ritany3.subject.infra.basic.entity.*;
import com.Ritany3.subject.infra.basic.service.*;
import com.Ritany3.subject.infra.entity.UserInfo;
import com.Ritany3.subject.infra.rpc.UserRpc;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
@Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectLikedDomainService subjeectLikedDominService;
    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject:rank:";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}",JSON.toJSONString(subjectInfoBO));
        }
        //假设我们都写在主流程里面
        // 判断type，单选的调用单选的service，多选的调用多选的
        // 一大堆的if
        //上一个工厂+策略的形式
        //一个工厂 包含了 4种类型，根据传入的type自动映射选择处理
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.converBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
       SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
       subjectInfoBO.setId(subjectInfo.getId());
       handler.add(subjectInfoBO);
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> mappingList = new LinkedList<>();
        categoryIds.forEach(categoryId->{
            labelIds.forEach(labelId->{
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(labelId);
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(mappingList);
        //同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("Ritany3");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);

    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo()-1)*subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.converBoToInfo(subjectInfoBO);
        int count = subjectInfoService.countByCindition(subjectInfo,subjectInfoBO.getCategoryId()
                ,subjectInfoBO.getLabelId());

        if (count == 0){
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList =  subjectInfoService.queryPage(subjectInfo
                ,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId()
                ,start,subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.converListToBO(subjectInfoList);
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId().intValue());
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.converOptionAndInfoToBO(optionBO,subjectInfo);
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNameList =labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());


        bo.setLabelName(labelNameList);


        bo.setLiked(subjeectLikedDominService.isLiked(subjectInfo.getId().toString(),LoginUtil.getLoginId()));
        bo.setLikedCount(subjeectLikedDominService.getLikedCount(subjectInfo.getId().toString()));
        return bo;
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);

    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if(log.isInfoEnabled()){
            log.info("getContributeList.typedTuples:{}",JSON.toJSONString(typedTuples));
        }

        if (CollectionUtils.isEmpty(typedTuples)){
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
           SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
           subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }
}
